package com.example.rocketmq.demo.consumer;

import com.example.rocketmq.demo.config.RocketMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 异步消费者
 */
@Slf4j
@Component
public class AsyncConsumer {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    private DefaultMQPushConsumer consumer;
    private ExecutorService executorService;

    @PostConstruct
    public void init() throws MQClientException {
        consumer = new DefaultMQPushConsumer(RocketMQConstant.CONSUMER_GROUP_NORMAL + "-async");
        consumer.setNamesrvAddr(nameServer);
        consumer.subscribe(RocketMQConstant.TOPIC_NORMAL, "*");

        // 设置消费模式为集群模式
        consumer.setMessageModel(MessageModel.CLUSTERING);

        // 设置从最新的消息开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);

        // 创建线程池用于异步处理消息
        executorService = Executors.newFixedThreadPool(10);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    // 使用CompletableFuture异步处理消息
                    CompletableFuture.runAsync(() -> {
                        try {
                            String content = new String(msg.getBody(), StandardCharsets.UTF_8);
                            log.info("异步消费者接收到消息: msgId={}, topic={}, tags={}, content={}",
                                    msg.getMsgId(), msg.getTopic(), msg.getTags(), content);

                            // 模拟耗时处理
                            Thread.sleep(500);

                            log.info("异步消费者处理完成消息: msgId={}", msg.getMsgId());
                        } catch (Exception e) {
                            log.error("异步处理消息失败", e);
                        }
                    }, executorService);
                }
                // 立即返回消费成功，实际处理在异步线程中进行
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
        log.info("异步消息消费者启动成功");
    }

    @PreDestroy
    public void destroy() {
        if (consumer != null) {
            consumer.shutdown();
            log.info("异步消息消费者已关闭");
        }

        if (executorService != null) {
            executorService.shutdown();
            log.info("异步消息处理线程池已关闭");
        }
    }
}
